#include "turtle.h"
#include <vector>
#include <typeinfo>

Turtle::Turtle(QuadTree<GameObject>* quadtree, float x, float y, int _layer) : DynamicObject()
{	
    worldMap = quadtree;
    if (mSprite.find("turtle") == mSprite.end())
    {	
        char path[100] = "Data\\Mario Sprites\\turtle.png";
        mSprite["turtle"] = new DXSprite(path, D3DCOLOR_XRGB(0, 0, 0), 1, 6);
    } 
    pSprite = mSprite["turtle"];
    posX = x;
    posY = y;
    layer = _layer;
    anima[0] = Animation(pSprite, 0, 1);
    anima[1] = Animation(pSprite, 2, 3);
    move = 0.1;
}

void Turtle::Update(unsigned int gameTime)
{	
    Rect prevBound = this->GetRectBound();
    posX += move;
    posY += 4;
    worldMap->RemoveObject(this);
    vector<GameObject*> temp = worldMap->GetObjects(prevBound.left, prevBound.top, (this->GetRectBound()).right, (this->GetRectBound()).bottom);
    for (vector<GameObject*>::iterator i = temp.begin(); i != temp.end(); ++i)
    {	
        if ((typeid(**i) == typeid(DynamicObject)) && IsCollide((*i)->GetRectBound(), this->GetRectBound()))
        {	
            if (prevBound.bottom <= ((*i)->GetRectBound()).top)
                posY = ((*i)->GetRectBound()).top - pSprite->GetHeight();
            else if (prevBound.top >= ((*i)->GetRectBound()).bottom)
                posY = ((*i)->GetRectBound()).bottom;
            else if (prevBound.right <= ((*i)->GetRectBound()).left)
            {	
                posX = ((*i)->GetRectBound()).left - pSprite->GetWidth();
                move = -0.1;
            }
            else if (prevBound.left >= ((*i)->GetRectBound()).right)
            {	
                posX = ((*i)->GetRectBound()).right;
                move = 0.1;
            }
        }
    }
    worldMap->InsertObject(this);
    return;
}

void Turtle::Render(unsigned int gameTime)
{	
    pSprite->SetPosition(posX - originX, posY - originY);
    if (move < 0)
        anima[0].Present(gameTime, 1000 / 0.5);
    else
        anima[1].Present(gameTime, 1000 / 0.5);
    return;
}